package es.usc.citius.servando.calendula.settings.notifications;

import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import es.usc.citius.servando.calendula.modules.ModuleManager;
import es.usc.citius.servando.calendula.modules.modules.StockModule;
import es.usc.citius.servando.calendula.mvp.BasePresenter;
import es.usc.citius.servando.calendula.util.LogUtil;
import es.usc.citius.servando.calendula.util.PreferenceKeys;
import es.usc.citius.servando.calendula.util.PreferenceUtils;

public class NotificationPrefsPresenter extends BasePresenter<NotificationPrefsContract.View> implements NotificationPrefsContract.Presenter {

    private final String TAG = "NotifPrefsPresenter";
    public static final int REQ_CODE_NOTIF_RINGTONE = 40;
    public static final int REQ_CODE_INSIST_RINGTONE = 41;

    private RingtoneNameResolver ringtoneNameResolver;

    public NotificationPrefsPresenter(RingtoneNameResolver ringtoneNameResolver) {
        this.ringtoneNameResolver = ringtoneNameResolver;
    }

    @Override
    public void start() {
        if (!ModuleManager.isEnabled(StockModule.ID)) {
            view.hideStockPref();
        }
        updateRingtoneSummaries();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            view.setVisibleNotificationManagementPref(true);
        } else {
            view.setVisibleNotificationManagementPref(false);
        }
    }

    @Override
    public void onResult(int reqCode, int result, Intent data) {
        LogUtil.d(TAG, "onResult() called with reqCode=$reqCode, result=$result, data=$data");
        if ((reqCode == REQ_CODE_INSIST_RINGTONE || reqCode == REQ_CODE_NOTIF_RINGTONE) && data != null) {
            Uri ringtone = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
            PreferenceKeys prefKey;
            if (reqCode == REQ_CODE_NOTIF_RINGTONE) {
                prefKey = PreferenceKeys.SETTINGS_NOTIFICATION_TONE;
            } else if (reqCode == REQ_CODE_INSIST_RINGTONE) {
                prefKey = PreferenceKeys.SETTINGS_INSISTENT_NOTIFICATION_TONE;
            } else {
                LogUtil.wtf(TAG, "invalid request!");
                throw new IllegalArgumentException("Invalid request code $reqCode");
            }
            LogUtil.d(TAG, "onResult: key=$prefKey, selected tone=$ringtone");
            PreferenceUtils.edit()
                    .putString(prefKey.key(), ringtone.toString() != null ? ringtone.toString() : "")
                    .apply();
            updateRingtoneSummaries();
        } else {
            LogUtil.d(TAG, "onResult: unexpected result or missing data");
        }
    }

    @Override
    public void selectNotificationRingtone() {
        doRequestRingtone(
                PreferenceKeys.SETTINGS_NOTIFICATION_TONE,
                REQ_CODE_NOTIF_RINGTONE,
                RingtoneManager.TYPE_NOTIFICATION
        );
    }

    @Override
    public void selectInsistentRingtone() {
        doRequestRingtone(
                PreferenceKeys.SETTINGS_INSISTENT_NOTIFICATION_TONE,
                REQ_CODE_INSIST_RINGTONE,
                RingtoneManager.TYPE_ALARM
        );
    }

    private void doRequestRingtone(PreferenceKeys pref, int requestCode, int ringtoneType) {
        Uri currentUri = findRingtoneUri(pref);
        LogUtil.d(
                TAG,
                "callSelectRingtone: currentUri=$currentUri, pref=$pref, requestCode=$requestCode"
        );

        view.requestRingtone(requestCode, ringtoneType, currentUri);
    }

    private Uri findRingtoneUri(PreferenceKeys key) {
        String currentTone =
                PreferenceUtils.getString(key, "default");
        if (currentTone.equals("")) {
            return null;
        } else if (currentTone.equals("default")) {
            return Settings.System.DEFAULT_NOTIFICATION_URI;
        } else {
            return Uri.parse(currentTone);
        }
    }

    private void updateRingtoneSummaries() {
        view.setNotificationRingtoneText(
                ringtoneNameResolver.resolveRingtoneName(
                        findRingtoneUri(
                                PreferenceKeys.SETTINGS_NOTIFICATION_TONE
                        )
                )
        );
        view.setInsistentRingtoneText(
                ringtoneNameResolver.resolveRingtoneName(
                        findRingtoneUri(
                                PreferenceKeys.SETTINGS_INSISTENT_NOTIFICATION_TONE
                        )
                )
        );
    }

}
